package ani.trainning.cacobatph.das;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.ksoap2.transport.ServiceConnection;
import org.ksoap2.transport.ServiceConnectionSE;
import org.kxml2.kdom.Element;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import ani.trainning.cacobatph.ConstantUtil;
import ani.trainning.cacobatph.R;
import ani.trainning.cacobatph.utilities;

public class Thr7_Das {


	public static final String LIST_YEARS = "listYears";

	public static final int ERREUR_WS = 0;
	public static final int RESULT_OK = 1;


	private final Handler mHandler;
	private final Context context;

	boolean noErrorServer = true;

	String user;
	String pass;

	private final String typeDas;

	// constructor
	public Thr7_Das(Handler handler, Context context,String _user, String _pass,String typeDas) {
		mHandler = handler;
		this.context = context;
		this.user=_user;
		this.pass=_pass;
		this.typeDas=typeDas;
	}

	public Thread createThread() {
		return new Thread() {
			@Override
			public void run() {
				// creation du message.
				try {

					String response = decoderJson(getParamMax());
					Message msg=new Message();

					msg.what = RESULT_OK;

					if(!noErrorServer)
						msg.what = ERREUR_WS;
					else{
						noErrorServer=true;
						JSONObject jSon = new JSONObject(response);
						String maxAnnee = jSon.getString("objet");
						String dasResponse=decoderJson(getDasDeposees());
						if(!noErrorServer)
							msg.what = ERREUR_WS;
						Bundle bundle= new Bundle();
						bundle.putStringArrayList(LIST_YEARS, (ArrayList<String>) getDasYears(dasResponse,Integer.parseInt(maxAnnee)));
						msg.obj =bundle;



					}
					mHandler.sendMessage(msg);

				} catch (Exception e) {
					Message msg=new Message();
					msg.obj = e;


					if (e instanceof IOException)
						msg.what = ConstantUtil.EXCEPTION_IO;
					else
						msg.what = ConstantUtil.EXCEPTIONS;

					Log.e("thread exeption : ", ""+e.getMessage());
					mHandler.sendMessage(msg);

				}

			}
		};
	}

	protected List<String> getDasYears(String jsonResponse,int maxAnnee) throws JSONException {
		List<Integer>maxYears= new ArrayList<Integer>();
		List<Integer>years= new ArrayList<Integer>();
		List<String>yearsToReturn= new ArrayList<String>();
		JSONObject jObject = new JSONObject(jsonResponse);
		JSONArray arrayYears=new JSONArray(jObject.getString("objet"));
		for (int i = 0; i < arrayYears.length(); i++) {
			years.add(Integer.parseInt(arrayYears.get(i).toString()));

		}
		//calculer maxAnnes en arriere maxYears
		Calendar calendar1= Calendar.getInstance();
		calendar1.setTime(new Date());
		calendar1.set(Calendar.MONTH, Calendar.JULY);
		calendar1.set(Calendar.DAY_OF_MONTH, 1);
		Calendar calendar2= Calendar.getInstance();
		calendar2.setTime(new Date());
		calendar2.set(Calendar.MONTH, Calendar.JULY);
		calendar2.set(Calendar.DAY_OF_MONTH, 31);
		Calendar currentCalendar= Calendar.getInstance();
		currentCalendar.setTime(new Date());

		int currentYearCpt;
		if(currentCalendar.after(calendar1) && currentCalendar.before(calendar2))
			currentYearCpt=currentCalendar.get(Calendar.YEAR);
		else
			currentYearCpt=currentCalendar.get(Calendar.YEAR)-1;
		maxYears.add(currentYearCpt);
		for (int i = 1; i < maxAnnee; i++) {
			currentYearCpt-=1;

			maxYears.add(currentYearCpt);

		}
		for (Integer year:maxYears) {
			if(typeDas.equals(Act6_Das.DAS_PRINCIPALE)){
				if(!years.contains(year))
					yearsToReturn.add(""+year);}
			else{
				if(years.contains(year))
					yearsToReturn.add(""+year);}
		}


		return yearsToReturn;

	}

	private String decoderJson(String response) throws Exception{

		JSONObject jSon = new JSONObject(response);
		int code = jSon.getInt("code");
		switch (code) {
		case 3:
			return jSon.getString("description");
		case 4:
			return jSon.getString("description");
		case 5:
			noErrorServer = false;
			return response;
		default:

			return response;
		}


	}
	private String getParamMax() throws Exception{


		SoapObject request = new SoapObject(context.getResources().getString(R.string.NAMESPACE),
				context.getResources().getString(R.string.PARAM_METHOD));

		PropertyInfo param = new PropertyInfo();
		param.setName(context.getResources().getString(R.string.NOM_PARAM));
		param.setType(String.class);
		param.setValue(context.getResources().getString(R.string.MAX_ANNEE));
		request.addProperty(param);
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
		envelope.dotNet = true;
		envelope.setOutputSoapObject(request);

		envelope.headerOut = new Element[1];
		envelope.headerOut[0] = utilities.buildAuthHeader(context, user, pass);


		HttpTransportSE androidHttpTransport = new HttpTransportSE(context.getResources().getString(R.string.URL)){
			@Override
			protected ServiceConnection getServiceConnection()
			throws IOException {
				return new ServiceConnectionSE(context.getResources().getString(R.string.URL), ConstantUtil.TIMEOUT);
			}
		};
		androidHttpTransport.call(context.getResources().getString(R.string.NAMESPACE)
				+ context.getResources().getString(R.string.PARAM_METHOD), envelope, null);

		String result = String.valueOf(envelope.getResponse());
		Log.i("chargement", "result : " + result);
		return result;

	}
	private String getDasDeposees() throws Exception{


		SoapObject request = new SoapObject(context.getResources().getString(R.string.NAMESPACE),
				context.getResources().getString(R.string.GET_DAS_METHOD));


		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
		envelope.dotNet = true;
		envelope.setOutputSoapObject(request);

		envelope.headerOut = new Element[1];
		envelope.headerOut[0] = utilities.buildAuthHeader(context, user, pass);


		HttpTransportSE androidHttpTransport = new HttpTransportSE(context.getResources().getString(R.string.URL));
		androidHttpTransport.call(context.getResources().getString(R.string.NAMESPACE)
				+ context.getResources().getString(R.string.GET_DAS_METHOD), envelope, null);

		String result = String.valueOf(envelope.getResponse());
		Log.i("chargement", "result : " + result);
		return result;

	}




}
